<template>
  <div class="dashboard-editor-container">
    <el-row :gutter="10">
      <el-col :xs="24" :sm="24" :lg="6">
        <div class="chart-wrapper">
          <div ref="humi" style="width: 100%;height: 300px;"></div>
        </div>
      </el-col>
      <el-col :xs="24" :sm="24" :lg="6">
        <div class="chart-wrapper">
          <div ref="temperature" style="width: 100%;height: 300px;"></div>
        </div>
      </el-col>
      <el-col :xs="24" :sm="24" :lg="6">
        <div class="chart-wrapper">
          <div ref="smoke" style="width: 100%;height: 300px;"></div>
        </div>
      </el-col>
      <el-col :xs="24" :sm="24" :lg="6">
        <div class="chart-wrapper">
          <div ref="pm25" style="width: 100%;height: 300px;"></div>
        </div>
      </el-col>
    </el-row>
    <el-card>
      <div slot="header">
        <span>大棚分布</span>
        <el-tag style="margin-left: 10px;">点击地图上标注可以查看环境分析</el-tag>
      </div>
      <div id="gdmap" style="width: 100%;height: 500px;"></div>
    </el-card>
  </div>
</template>

<script>
import { report4Hour } from '@/api/system/ghMonitor'
import { listGreenhouse } from "@/api/system/greenhouse";
import * as echarts from 'echarts';
import AMapLoader from "@amap/amap-jsapi-loader";
import setting, { title } from '../settings';
import { init } from 'echarts/lib/echarts';

export default {
  name: 'Index',
  data() {
    return {
      userId: null,
      map: null,
      location: {
        lng: null,
        lat: null,
      },
      greenHouseList: [],
      reportData: {
        times: [],
        temperatures: [],
        humi: [],
        smoke: [],
        pm25: [],
      },
      // 查询参数
      queryParams: {
        greenhouseId: null,
        start: null,
      },
      mapOptions: {
        version: "2.0",
        securityJsCode: setting.amap.securityJsCode,
        key: setting.amap.key, // 申请好的Web端开发者Key，首次调用 load 时必填
        plugins: ["AMap.Scale", "AMap.PlaceSearch", "AMap.AutoComplete"], //需要使用的的插件列表，如比例尺'AMap.Scale'，支持添加多个如：['...','...']
      },
      smokeChart: null,
      tmpChart: null,
      humiChart: null,
      pm25Chart: null,
      markerList: [],
    }
  },
  created() {
    this.getReportData();
    this.getGreenHouseList();
  },
  mounted() {
    this.humiChart = echarts.init(this.$refs.humi);
    this.tmpChart = echarts.init(this.$refs.temperature);
    this.smokeChart = echarts.init(this.$refs.smoke);
    this.pm25Chart = echarts.init(this.$refs.pm25);
    this.init();
    //this.loadHealth();
    //this.intervalId = setInterval(this.loadHealth, 5000);
    //this.intervalId2 = setInterval(this.getFencesAlert, 10000);
    //this.loadLocation();
    //this.loadFences();
  },
  unmounted() {
    this.map?.destroy();
  },
  beforeDestroy() {

  },
  methods: {
    init() {
      AMapLoader.load(this.mapOptions).then((AMap) => {
        this.map = new AMap.Map("gdmap", {
          // 设置地图容器id
          zoom: 15, // 初始化地图级别
        });
        // 添加比例尺
        this.map.addControl(new AMap.Scale());
      })
      this.initChart();
    },
    initChart() {
      this.displayHumi();
      this.displayTemperature();
      this.displaySmoke();
      this.displayPM25();
    },
    locatePos() {
      if (this.location.lng && this.location.lat) {
        this.map.setCenter([this.location.lng, this.location.lat]);
        this.map.setZoom(15);
      }
    },
    async initAMap() {
      window._AMapSecurityConfig = {
        securityJsCode: this.mapOptions.securityJsCode,
      };
      AMapLoader.reset();
    },
    //显示地图标注
    loadLocation() {
      this.initAMap().then(() => {
        let _this = this;
        AMapLoader.load(this.mapOptions).then((AMap) => {
          this.map = new AMap.Map("gdmap", {
            // 设置地图容器id
            zoom: 15, // 初始化地图级别
          });
          // 添加比例尺
          this.map.addControl(new AMap.Scale());
          for (let i = 0; i < this.greenHouseList.length; i++) {
            let greenHouse = this.greenHouseList[i];
            let lng = greenHouse.lng;
            let lat = greenHouse.lat;
            if (lng && lat) {
              //标注
              let marker = new AMap.Marker({
                icon: "http://a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-red.png",
                position: [lng, lat],
                offset: new AMap.Pixel(-13, -30),
                title: greenHouse.name,
                // label:{
                //   offset: new AMap.Pixel(0, 0),
                //   content: greenHouse.name,
                //   direction: 'top'
                // }
              });
              marker.setMap(this.map);
              marker.on('click', (e) => {
                console.log('Marker 被点击了');
                _this.queryParams.greenhouseId = greenHouse.id;
                _this.getReportData();
              });
              this.markerList.push(marker);
            }
          }
          // 缩放地图到合适的视野级别
          this.map.setFitView(this.markerList)
        });
      });
    },
    /** 获取大棚选项 */
    getGreenHouseList() {
      let queryParams = {
      }
      listGreenhouse(queryParams).then(response => {
        this.greenHouseList = response.rows;
        this.loadLocation();
      });
    },
    getReportData() {
      report4Hour(this.queryParams).then(response => {
        const data = response.data
        this.reportData.times = data.times
        this.reportData.temperatures = data.temperature
        this.reportData.humi = data.humi
        this.reportData.smoke = data.smoke
        this.reportData.pm25 = data.pm25
        this.initChart();
      })
    },
    displayHumi() {
      let options = {
        title: {
          text: '湿度',
          left: 'center',
          top: 'top',
          textStyle: {
            fontSize: 15,
            // color: '#000'
          }
        },
        tooltip: {
          show: false
        },
        toolbox: {
          show: false
        },
        xAxis: {
          type: 'category',
          data: this.reportData.times,
          axisLabel: {
            rotate: -45,
            fontSize: 10,
          },
          axisLine: {
            show: true,
            // lineStyle: {
            //     color: '#E5DAD1' // x轴颜色
            // }
          },
          splitLine: { // x轴网格线（垂直方向）
            show: true,
            // lineStyle: {
            //     color: '#E5DAD1', // 网格线颜色（支持十六进制、RGB等）
            // }
          }
        },
        yAxis: [{
          type: 'value',
          name: '%',
          position: 'left',
          min: 0, // 手动设置最小值
          max: 100, // 手动设置最大值
          axisLine: {
            show: true,
            // lineStyle: {
            //     color: '#E5DAD1' // y轴颜色
            // }
          },
          splitLine: { // y轴网格线（水平方向）
            show: true,
            // lineStyle: {
            //     color: '#E5DAD1',
            // }
          }
        }],
        series: [{
          name: '湿度',
          type: 'line',
          data: this.reportData.humi,
          yAxisIndex: 0,
          smooth: true,
          lineStyle: {
            width: 2,
            // color: '#FFA94E'
          },
          itemStyle: {
            // color: '#FFA94E'
          }
        }]
      }
      this.humiChart.setOption(options);
    },
    displayTemperature() {
      let option = {
        title: {
          text: '温度',
          left: 'center',
          top: 'top',
          textStyle: {
            fontSize: 15,
            // color: '#000'
          }
        },
        tooltip: {
          show: false
        },
        toolbox: {
          show: false
        },
        xAxis: {
          type: 'category',
          data: this.reportData.times,
          axisLabel: {
            rotate: -45,
            fontSize: 10,
          },
          axisLine: {
            show: true,
            lineStyle: {
              // color: '#E5DAD1' // x轴颜色
            }
          },
          splitLine: { // x轴网格线（垂直方向）
            show: true,
            lineStyle: {
              // color: '#E5DAD1', // 网格线颜色（支持十六进制、RGB等）
            }
          }
        },
        yAxis: [{
          type: 'value',
          name: '°C',
          position: 'left',
          min: 0, // 手动设置最小值
          max: 100, // 手动设置最大值
          axisLine: {
            show: true,
            lineStyle: {
              // color: '#E5DAD1' // y轴颜色
            }
          },
          splitLine: { // y轴网格线（水平方向）
            show: true,
            lineStyle: {
              // color: '#E5DAD1',
            }
          }
        }],
        series: [{
          name: '温度',
          type: 'line',
          data: this.reportData.temperatures,
          yAxisIndex: 0,
          smooth: true,
          lineStyle: {
            width: 2,
            // color: '#FFA94E'
          },
          itemStyle: {
            // color: '#FFA94E'
          }
        }]
      };
      this.tmpChart.setOption(option);
    },
    displaySmoke() {
      let options = {
        title: {
          text: '烟雾',
          left: 'center',
          top: 'top',
          textStyle: {
            fontSize: 15,
            // color: '#000'
          }
        },
        tooltip: {
          show: false
        },
        toolbox: {
          show: false
        },
        xAxis: {
          type: 'category',
          data: this.reportData.times,
          axisLabel: {
            rotate: -45,
            fontSize: 10,
          },
          axisLine: {
            show: true,
            lineStyle: {
              // color: '#E5DAD1' // x轴颜色
            }
          },
          splitLine: { // x轴网格线（垂直方向）
            show: true,
            lineStyle: {
              // color: '#E5DAD1', // 网格线颜色（支持十六进制、RGB等）
            }
          }
        },
        yAxis: [{
          type: 'value',
          name: '%',
          position: 'left',
          min: 0, // 手动设置最小值
          max: 200, // 手动设置最大值
          axisLine: {
            show: true,
            lineStyle: {
              // color: '#E5DAD1' // y轴颜色
            }
          },
          splitLine: { // y轴网格线（水平方向）
            show: true,
            lineStyle: {
              // color: '#E5DAD1',
            }
          }
        }],
        series: [{
          name: '烟雾',
          type: 'line',
          data: this.reportData.smoke,
          yAxisIndex: 0,
          smooth: true,
          lineStyle: {
            width: 2,
            // color: '#FFA94E'
          },
          itemStyle: {
            // color: '#FFA94E'
          }
        }]
      };
      this.smokeChart.setOption(options);
    },
    displayPM25() {
      let options = {
        title: {
          text: 'PM2.5',
          left: 'center',
          top: 'top',
          textStyle: {
            fontSize: 15,
            // color: '#000'
          }
        },
        tooltip: {
          show: false
        },
        toolbox: {
          show: false
        },
        xAxis: {
          type: 'category',
          data: this.reportData.times,
          axisLabel: {
            rotate: -45,
            fontSize: 10,
          },
          axisLine: {
            show: true,
            lineStyle: {
              // color: '#E5DAD1' // x轴颜色
            }
          },
          splitLine: { // x轴网格线（垂直方向）
            show: true,
            lineStyle: {
              // color: '#E5DAD1', // 网格线颜色（支持十六进制、RGB等）
            }
          }
        },
        yAxis: [{
          type: 'value',
          name: '',
          position: 'left',
          min: 0, // 手动设置最小值
          max: 300, // 手动设置最大值
          axisLine: {
            show: true,
            lineStyle: {
              // color: '#E5DAD1' // y轴颜色
            }
          },
          splitLine: { // y轴网格线（水平方向）
            show: true,
            lineStyle: {
              // color: '#E5DAD1',
            }
          }
        }],
        series: [{
          name: 'PM2.5',
          type: 'line',
          data: this.reportData.pm25,
          yAxisIndex: 0,
          smooth: true,
          lineStyle: {
            width: 2,
            // color: '#FFA94E'
          },
          itemStyle: {
            // color: '#FFA94E'
          }
        }]
      };
      this.pm25Chart.setOption(options);
    },
  }
}
</script>

<style lang="scss" scoped>
.dashboard-editor-container {
  padding: 20px;
  background-color: rgb(240, 242, 245);
  position: relative;

  .chart-wrapper {
    background: #fff;
    padding: 16px 16px 0;
    margin-bottom: 20px;
  }
}

@media (max-width:1024px) {
  .chart-wrapper {
    padding: 8px;
  }
}
</style>
